//
//  GTListLoader.m
//  news
//
//  Copyright © 2022 sinosun. All rights reserved.
//

#import "GTListLoader.h"
#import <AFNetworking.h>
#import "GTListItem.h"

@implementation GTListLoader


- (void)loadListData{
    
    NSString *strUrl = @"http://v.juhe.cn/toutiao/index?type=&page=&page_size=&is_filter=&key=97ad001bfcc2082e2eeaf798bad3d54e";
    // 初始化 NSURL
    NSURL *url = [NSURL URLWithString:strUrl];
    // 初始化 NSURLRequest
    //NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 初始化 session
    NSURLSession *session = [NSURLSession sharedSession];
    // 初始化 NSURLSessionDataTask
    //NSURLSessionDataTask *sessionTask = [session dataTaskWithRequest:request];
    NSURLSessionDataTask *sessionTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        
        NSError *jsonError;
        NSDictionary *httpResult = [NSJSONSerialization JSONObjectWithData:data options:(0) error:&jsonError];
        NSLog(@"%@", httpResult);
        
        NSDictionary *result = [httpResult objectForKey:@"result"];
        NSArray *dataArray = [result objectForKey:@"data"];
        for (id data in dataArray) {
            GTListItem *item = [[GTListItem alloc] init];
            [item configureWithDictionary:(NSDictionary *)data];
        }
        
    }];
    
    [sessionTask resume];
}

- (void)loadListDataWithBlock:(GTListItemLoadFinished)finishedBlock
{
    
    // 先用本地缓存的数据，初始化列表
    NSArray <GTListItem *> *dataArray = [self _readDataFromLocal];
    if (dataArray) {
        finishedBlock(YES, dataArray);
    }
    
    NSString *strUrl = @"http://v.juhe.cn/toutiao/index?type=&page=&page_size=&is_filter=&key=97ad001bfcc2082e2eeaf798bad3d54e";
    // 初始化 NSURL
    NSURL *url = [NSURL URLWithString:strUrl];
    // 初始化 NSURLRequest
    //NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 初始化 session
    NSURLSession *session = [NSURLSession sharedSession];
    // 初始化 NSURLSessionDataTask
    //NSURLSessionDataTask *sessionTask = [session dataTaskWithRequest:request];
    
    __weak typeof(self) weakself = self;
    NSURLSessionDataTask *sessionTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        __strong typeof(weakself) strongself = weakself;
        
        NSError *jsonError;
        NSDictionary *httpResult = [NSJSONSerialization JSONObjectWithData:data options:(0) error:&jsonError];
        NSLog(@"%@", httpResult);
        
        NSDictionary *result = [httpResult objectForKey:@"result"];
        NSArray *dataArray = [result objectForKey:@"data"];
        NSMutableArray *itemArray = [[NSMutableArray alloc] init];
        for (id data in dataArray) {
            GTListItem *item = [[GTListItem alloc] init];
            [item configureWithDictionary:(NSDictionary *)data];
            [itemArray addObject:item];
        }
        
        [self _archiveListDataWithArray:itemArray];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (finishedBlock) {
                finishedBlock(nil == jsonError, itemArray);
            }
        });
       
    }];
    
    [sessionTask resume];
    
    [self getDocumentsPath];
}

- (void)_archiveListDataWithArray:(NSArray<GTListItem *> *)array{
    
    // 通过 NSSearchPathForDirectoriesInDomains 读到沙盒路径
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [pathArray firstObject];
    NSLog(@"cachePath path: %@",cachePath);
    
    // NSFileManager 是一个单例
    NSFileManager *filemanager = [NSFileManager defaultManager];
    NSError *error;
    
    // 创建一个文件夹
    NSString *dataDirPath = [cachePath stringByAppendingPathComponent:@"GTData"];
    [filemanager createDirectoryAtPath:dataDirPath withIntermediateDirectories:YES attributes:nil error:&error];
    
    // 序列化数据
    NSData *listData = [NSKeyedArchiver archivedDataWithRootObject:array requiringSecureCoding:YES error:nil];
    
    // 创建一个文件,并写入序列化数据
    NSString *listFile = [dataDirPath stringByAppendingPathComponent:@"GTList"];
    [filemanager createFileAtPath:listFile contents:listData attributes:nil];
    
    // 读取文件数据
    NSData *readData = [filemanager contentsAtPath:listFile];
    
    // 反序列化
    id unarchiveObj = [NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithObjects:[NSArray class], [GTListItem class], nil] fromData:readData error:&error];
    
    [[NSUserDefaults standardUserDefaults] setObject:@"abc" forKey:@"test"];
    NSString *test = [[NSUserDefaults standardUserDefaults] objectForKey:@"test"];
    NSLog(@"test is %@", test);
}

- (void)loadListDataAF{
    
    NSString *strUrl = @"http://www.baidu.com";
 
    [[AFHTTPSessionManager manager] GET:strUrl parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"success");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"failure");
    }];
}

- (void)getDocumentsPath{
    
    // 通过 NSSearchPathForDirectoriesInDomains 读到沙盒路径
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [pathArray firstObject];
    NSLog(@"cachePath path: %@",cachePath);
    
    // NSFileManager 是一个单例
    NSFileManager *filemanager = [NSFileManager defaultManager];
    NSError *error;
    
    // 创建一个文件夹
    NSString *dataDirPath = [cachePath stringByAppendingPathComponent:@"GTData"];
    [filemanager createDirectoryAtPath:dataDirPath withIntermediateDirectories:YES attributes:nil error:&error];
    
    // 将字符串通过UTF8编码转为二进制流
    NSData *data = [@"abc" dataUsingEncoding:(NSUTF8StringEncoding)];
    
    // 创建一个文件,并写入数据
    NSString *listFile = [dataDirPath stringByAppendingPathComponent:@"GTList"];
    [filemanager createFileAtPath:listFile contents:data attributes:nil];
    
    
    // 查询文件是否存在,绝对路径
    BOOL fileExist = [filemanager fileExistsAtPath:listFile];
    
    // 删除文件,绝对路径
    if (fileExist) {
        // [filemanager removeItemAtPath:listFile error:&error];
    }
    

#pragma mark - NSFileHandle 读文件，写文件，读文件的一部分，调整文件的offset
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:listFile];
    // 调整文件的offset至末尾
    [fileHandle seekToEndOfFile];
    // 往末尾追加数据
    [fileHandle writeData:[@"def" dataUsingEncoding:(NSUTF8StringEncoding)]];
    // 刷新文件
    [fileHandle synchronizeFile];
    // 关闭文件
    [fileHandle closeFile];
    
    
}

- (NSArray <GTListItem *>*)_readDataFromLocal{
    
    // 通过 NSSearchPathForDirectoriesInDomains 读到沙盒路径
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [pathArray firstObject];
    NSLog(@"cachePath path: %@",cachePath);
    
    // NSFileManager 是一个单例
    NSFileManager *filemanager = [NSFileManager defaultManager];
    NSError *error;
    
    // 文件夹
    NSString *dataDirPath = [cachePath stringByAppendingPathComponent:@"GTData"];
   
    // 文件绝对路径
    NSString *listFile = [dataDirPath stringByAppendingPathComponent:@"GTList"];
   
    // 读取文件数据
    NSData *readData = [filemanager contentsAtPath:listFile];
    
    // 反序列化
    id unarchiveObj = [NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithObjects:[NSArray class], [GTListItem class], nil] fromData:readData error:&error];
    
    if ([unarchiveObj isKindOfClass:[NSArray class]] && [unarchiveObj count] > 0) {
        return (NSArray <GTListItem *>*)unarchiveObj;
    }
    return nil;
}
@end
